package me.flyray.crm.core.biz;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.biz.common.admin.pay.request.PayForAnotherApplyRequest;
import com.github.wxiaoqi.security.biz.common.admin.pay.request.PayForAnotherRequest;
import com.github.wxiaoqi.security.biz.common.crm.request.FreezeRequest;
import com.github.wxiaoqi.security.biz.common.crm.request.MerchantPayForAnotherBankParam;
import com.github.wxiaoqi.security.biz.common.crm.request.MerchantPayForAnotherBankRequest;
import com.github.wxiaoqi.security.biz.common.crm.request.UnFreezeAndOutAccountRequest;
import com.github.wxiaoqi.security.biz.common.msg.BizResponseCode;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.enums.CustomerTypeEnums;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.msg.TradeType;
import com.github.wxiaoqi.security.common.util.EntityUtils;
import com.github.wxiaoqi.security.common.util.SHA256Utils;

import me.flyray.crm.core.client.BankCodeBizService;
import me.flyray.crm.core.entity.CustomerBase;
import me.flyray.crm.core.entity.FreezeJournal;
import me.flyray.crm.core.entity.MerchantBase;
import me.flyray.crm.core.entity.MerchantPayForAnotherBank;
import me.flyray.crm.core.mapper.CustomerBaseMapper;
import me.flyray.crm.core.mapper.FreezeJournalMapper;
import me.flyray.crm.core.mapper.MerchantBaseMapper;
import me.flyray.crm.core.mapper.MerchantPayForAnotherBankMapper;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 商户提现银行卡信息表
 * @author he
 */
@Service
public class MerchantPayForAnotherBankBiz extends BaseBiz<MerchantPayForAnotherBankMapper, MerchantPayForAnotherBank> {

	private static final Logger logger = LoggerFactory.getLogger(MerchantPayForAnotherBankBiz.class);

	@Autowired
	private BankCodeBizService bankCodeBizService;
	@Autowired
	private CommonFreezeUnFreezeBiz commonFreezeUnFreezeBiz;
	@Autowired
	private CommonOutAccountBiz outAccountBiz;
	@Autowired
	private PayChannelConfigBiz payChannelConfigBiz;
	@Autowired
	private MerchantBaseMapper merchantBaseMapper;
	@Autowired
	private CustomerBaseMapper customerBaseMapper;
	@Autowired
	private FreezeJournalMapper freezeJournalMapper;

	/**
	 * 代付申请
	 * @return
	 */
	public Map<String, Object> payForAnotherApply(PayForAnotherApplyRequest payForAnotherApplyRequest){
		logger.info("代付申请开始..........{}",EntityUtils.beanToMap(payForAnotherApplyRequest));

		BigDecimal fee = BigDecimal.ZERO;
		//计算手续费
		Map<String, Object> queryMerChannelFee = payChannelConfigBiz.getPayChannelFee(EntityUtils.beanToMap(payForAnotherApplyRequest));
		logger.info("代付申请手续费.......{}",queryMerChannelFee);
		if(BizResponseCode.OK.getCode().equals(queryMerChannelFee.get("code"))){
			String feeStr = (String)queryMerChannelFee.get("fee");
			fee = new BigDecimal(feeStr);
		}

		Map<String, Object> param = new HashMap<String, Object>();
		String orderId = String.valueOf(SnowFlake.getId());
		param.put("platformId",payForAnotherApplyRequest.getPlatformId());
		param.put("merchantId",payForAnotherApplyRequest.getMerchantId());
		param.put("bankName", payForAnotherApplyRequest.getBankName());
		param.put("bankAccountName", payForAnotherApplyRequest.getBankAccountName());
		param.put("bankAccountNo", payForAnotherApplyRequest.getBankNo());
		param.put("orderId", orderId);
		param.put("amount", payForAnotherApplyRequest.getAmount());
		param.put("payFee", String.valueOf(fee));
		param.put("type", "01");//用户提现
		Map<String, Object> payForAnotherApply = bankCodeBizService.payForAnotherApply(param);
		logger.info("paycore代付申请结束..........{}",payForAnotherApply);
		if(BizResponseCode.OK.getCode().equals(payForAnotherApply.get("code"))){
			//冻结商户可提现余额账户
			FreezeRequest freezeRequest = new FreezeRequest();
			freezeRequest.setPlatformId(payForAnotherApplyRequest.getPlatformId());
			freezeRequest.setMerchantId(payForAnotherApplyRequest.getMerchantId());
			freezeRequest.setCustomerType(CustomerTypeEnums.CUST_MERCHANT.getCode());
			freezeRequest.setMerchantType(CustomerTypeEnums.CUST_MERCHANT.getCode());//商户
			freezeRequest.setAccountType("ACC013");//可提现余额账户
			freezeRequest.setFreezeAmt(payForAnotherApplyRequest.getAmount());
			freezeRequest.setTradeType(TradeType.WITHDRAW.getCode());// 01：支付，02：退款，03：提现，04：充值，05：预收款，06：消费，07：结算，08：领取
			freezeRequest.setOrderNo(orderId);
			commonFreezeUnFreezeBiz.freeze(freezeRequest);
		}
		logger.info("代付申请结束..........");
		return payForAnotherApply;
	}

	/**
	 * 代付
	 * @return
	 */
	public Map<String, Object> payForAnother(PayForAnotherRequest payForAnotherRequest){
		logger.info("代付开始..........{}",EntityUtils.beanToMap(payForAnotherRequest));
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("platformId",payForAnotherRequest.getPlatformId());
		param.put("orderId", payForAnotherRequest.getOrderId());
		Map<String, Object> payForAnother = bankCodeBizService.payForAnother(param);
		logger.info("paycore代付结束..........{}",payForAnother);
		if(BizResponseCode.OK.getCode().equals(payForAnother.get("code"))){
			if("01".equals(payForAnotherRequest.getType())){//用户提现
				FreezeJournal freezeJournal=new FreezeJournal();
				freezeJournal.setPlatformId(payForAnotherRequest.getPlatformId());
				freezeJournal.setOrderNo(payForAnotherRequest.getOrderId());
				freezeJournal.setTccFlag("1");//生效
				FreezeJournal selectOne = freezeJournalMapper.selectOne(freezeJournal);
				if(null == selectOne){
					Map<String, Object> sesultMap = new HashMap<String, Object>();
					sesultMap.put("code", BizResponseCode.FREEZE_ORDER_NOTEXIST.getCode());
					sesultMap.put("message", BizResponseCode.FREEZE_ORDER_NOTEXIST.getMessage());
					return sesultMap;
				}
				//用户余额账户解冻并出账
				UnFreezeAndOutAccountRequest unFreAndOutAccountRequest = new UnFreezeAndOutAccountRequest();
				unFreAndOutAccountRequest.setPlatformId(payForAnotherRequest.getPlatformId());
				unFreAndOutAccountRequest.setMerchantId(payForAnotherRequest.getMerchantId());
				unFreAndOutAccountRequest.setUnFreezeAmt((String) payForAnother.get("amount"));
				unFreAndOutAccountRequest.setCustomerType(CustomerTypeEnums.CUST_PERSONAL.getCode());
				//后期改为保存到提现表查出账户类型
				unFreAndOutAccountRequest.setAccountType("ACC011");//火钻账户
				unFreAndOutAccountRequest.setFreezeId(String.valueOf(SnowFlake.getId()));
				unFreAndOutAccountRequest.setOrderNo(payForAnotherRequest.getOrderId());
				unFreAndOutAccountRequest.setPersonalId(selectOne.getCustomerNo());
				unFreAndOutAccountRequest.setTradeType(TradeType.WITHDRAW.getCode());//// 01：支付，02：退款，03：提现，04：充值，05：预收款，06：消费，07：结算，08：领取
				outAccountBiz.unFreAndOutAccount(unFreAndOutAccountRequest);
			}else{//商户提现
				//解冻并出账商户可提现余额账户
				UnFreezeAndOutAccountRequest unFreAndOutAccountRequest = new UnFreezeAndOutAccountRequest();
				unFreAndOutAccountRequest.setPlatformId(payForAnotherRequest.getPlatformId());
				unFreAndOutAccountRequest.setMerchantId(payForAnotherRequest.getMerchantId());
				unFreAndOutAccountRequest.setFreezeId(String.valueOf(SnowFlake.getId()));
				unFreAndOutAccountRequest.setCustomerType(CustomerTypeEnums.CUST_MERCHANT.getCode());
				unFreAndOutAccountRequest.setMerchantType(CustomerTypeEnums.CUST_MERCHANT.getCode());//商户
				unFreAndOutAccountRequest.setAccountType("ACC013");//可提现余额账户
				unFreAndOutAccountRequest.setUnFreezeAmt((String) payForAnother.get("amount"));
				unFreAndOutAccountRequest.setOrderNo(payForAnotherRequest.getOrderId());
				unFreAndOutAccountRequest.setTradeType(TradeType.WITHDRAW.getCode());//// 01：支付，02：退款，03：提现，04：充值，05：预收款，06：消费，07：结算，08：领取
				outAccountBiz.unFreAndOutAccount(unFreAndOutAccountRequest);
			}
		}
		return payForAnother;
	}


	/**
	 * 列表
	 * @param bean
	 * @return
	 */
	public TableResultResponse<MerchantPayForAnotherBank> payForAnotherBankList(MerchantPayForAnotherBankRequest param){
		Example example = new Example(MerchantPayForAnotherBank.class);
		Criteria criteria = example.createCriteria();
		if(!StringUtils.isEmpty(param.getPlatformId())) {
			criteria.andEqualTo("platformId",param.getPlatformId());
		}
		if(!StringUtils.isEmpty(param.getMerchantId())) {
			criteria.andEqualTo("merchantId",param.getMerchantId());
		}
		Page<MerchantPayForAnotherBank> result = PageHelper.startPage(param.getPage(), param.getLimit());
		List<MerchantPayForAnotherBank> list = mapper.selectByExample(example);
		return new TableResultResponse<MerchantPayForAnotherBank>(result.getTotal(), list);
	}

	/** 
	 * 添加
	 */
	public Map<String, Object> addPayForAnotherBank(MerchantPayForAnotherBankParam param){
		Map<String, Object> respMap = new HashMap<String, Object>();
		//保存交易密码
		if(!StringUtils.isEmpty(param.getPassword())){
			MerchantBase merchantBase = new MerchantBase();
			merchantBase.setPlatformId(param.getPlatformId());
			merchantBase.setMerchantId(param.getMerchantId());
			MerchantBase selectMerchantBase = merchantBaseMapper.selectOne(merchantBase);
			if(null != selectMerchantBase){
				String customerId = selectMerchantBase.getCustomerId();
				CustomerBase customerBase = new CustomerBase();
				customerBase.setPlatformId(param.getPlatformId());
				customerBase.setCustomerId(customerId);
				CustomerBase selectCustomerBase = customerBaseMapper.selectOne(customerBase);
				if(null != selectCustomerBase){
					selectCustomerBase.setPayPassword(SHA256Utils.SHA256(SHA256Utils.SHA256(param.getPassword())+param.getMerchantId()));
					selectCustomerBase.setPayPasswordErrorCount(0);
					selectCustomerBase.setPayPasswordStatus("00");
					customerBaseMapper.updateByPrimaryKey(selectCustomerBase);
				}
			}
		}

		try {
			MerchantPayForAnotherBank config = new MerchantPayForAnotherBank();
			BeanUtils.copyProperties(param, config);
			if (mapper.insertSelective(config) > 0) {
				respMap.put("code", BizResponseCode.OK.getCode());
				respMap.put("message", BizResponseCode.OK.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			respMap.put("code", BizResponseCode.SERVICE_NOT_AVALIABLE.getCode());
			respMap.put("message", BizResponseCode.SERVICE_NOT_AVALIABLE.getMessage());
		}
		return respMap;
	}

	/**
	 * 删除
	 */
	public MerchantPayForAnotherBank deletePayForAnotherBank(MerchantPayForAnotherBankParam param){
		MerchantPayForAnotherBank config1 = null;
		try {
			MerchantPayForAnotherBank config = new MerchantPayForAnotherBank();
			BeanUtils.copyProperties(param, config);
			config.setId(Integer.valueOf(param.getId()));
			config1 = mapper.selectOne(config);
			mapper.delete(config);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return config1;
	}


	/**
	 * 修改
	 */
	public MerchantPayForAnotherBank updatePayForAnotherBank(MerchantPayForAnotherBankParam param){
		MerchantPayForAnotherBank config1 = null;
		try {
			MerchantPayForAnotherBank config = new MerchantPayForAnotherBank();
			BeanUtils.copyProperties(param, config);
			config.setId(Integer.valueOf(param.getId()));
			config1 = mapper.selectOne(config);
			mapper.updateByPrimaryKey(config);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return config1;
	}
}